package com.cn.wx.servlet.login;

import com.cn.wx.model.UserModel;
import com.cn.wx.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        登陆:第一步：查询操作，查询是否有当前用户名，如果不正确，返回提示
//        第二步：如果用户名正确，比较密码，如果密码正确，提示登陆成功，并返回登陆成功页面
//        如果密码不正取，提示，密码不正确
//        第三步：用户名没有，提示用户名不存在，请注册用户
//        每一个功能写一个HttpServlet
        LoginService loginService = new LoginService();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserModel userModel = new UserModel();

        userModel.setUsername(username);
        userModel.setPassword(password);
        String result = loginService.getUserByName(userModel);
        req.setAttribute("result", result);

        //当result为1时表示登陆成功，返回用户管理页面，否则返回登陆页面重新登陆
        if (result.equals("1")) {
            List<UserModel> list = loginService.getAll(10,1);
            req.setAttribute("list", list);
            req.getSession().setAttribute("username",userModel.getUsername());

            req.getRequestDispatcher("/back/UserManage.jsp").forward(req, resp);//页面转发
        } else {
            req.getRequestDispatcher("/back/login.jsp").forward(req, resp);//页面转发
        }


    }
}
